package com.swn.cm.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.swn.common.constants.ICommonConstants;
import com.swn.common.util.DbHelper;
import com.swn.common.util.IID;
import com.swn.common.util.JSONUtil;


/**
 * 角色管理的类
 * @author 董士明
 * @date 2018-01-11
 *
 */
@Service("roleService")
public class RoleService {
	private static Logger logger = Logger.getLogger("RoleService.class");
	@Autowired
	DbHelper dbHelper;
	
	/**
	 * 查询角色
	 * @return
	 */
	public List<Map<String, Object>> queryRoleList()throws Exception{
		StringBuilder sql = new StringBuilder();
		sql.append("   select r.id,r.name,r.remark,r.create_user_id,r.create_time,r.update_user_id,r.last_update_time ")
		   .append("   ,ifnull((")
		   .append("      select group_concat(menu_name) menu_name from shop_cm_role_warrant where role_id=r.id")
		   .append("    ),'')menu_names")
		   .append("   ,ifnull((")
		   .append("      select group_concat(menu_id) menu_id from shop_cm_role_warrant where role_id=r.id")
		   .append("    ),'')menu_ids")
		   .append("   from shop_cm_role r  order by r.create_time desc")
		   .append("");
		return dbHelper.queryForList(sql.toString(), null);
	}
	
	/**
	 * 查询角色被授权的菜单中的具体功能
	 * @return
	 */
	public List<Map<String, Object>> queryRoleMenuList()throws Exception{
		StringBuilder sql = new StringBuilder();
		sql.append("   select r.id,r.name")
		   .append("   ,ifnull((")
		   .append("      select group_concat(menu_warrant_names) menu_warrant_names from shop_cm_role_warrant where role_id=r.id")
		   .append("    ),'')menu_warrant_names")
		   .append("   from shop_cm_role r  order by r.create_time desc")
		   .append("");
		return dbHelper.queryForList(sql.toString(), null);
	}
	/**
	 * 查询角色具体每个菜单对应的具体功能组装成list用于tree展示
	 * @return
	 */
	public List<Map<String, Object>> queryRoleAuthorizedList(String roleID)throws Exception{
		List<Map<String, Object>> auList=new ArrayList<Map<String,Object>>();
		List<Map<String, Object>> newList=new ArrayList<Map<String,Object>>();
		StringBuilder sql = new StringBuilder();
		sql.append("   select r.id warrantID,r.menu_id id,r.menu_name name,0 pId,ifnull(r.menu_warrant,'')menu_warrant,ifnull(r.menu_warrant_names,'')menu_warrant_names,ifnull(m.menu_warrant,'') m_warrant,ifnull(m.menu_warrant_name,'') m_name")
		   .append("   from shop_cm_role_warrant r left join shop_cm_menu m on r.menu_id=m.id")
		   .append("   where r.final_node=1  and r.role_id='").append(roleID).append("' order by m.id");
		auList= dbHelper.queryForList(sql.toString(), null);
		if(auList!=null &&auList.size()>0){
			 for(Map<String, Object> mm:auList){
				 if(!mm.get("m_warrant").toString().equals("")){
					  String[] m_warrantID=mm.get("m_warrant").toString().split(",");              //最终子节点对应的所有具体功能id
					  String[] m_warrantName=mm.get("m_name").toString().split(",");               //最终子节点对应的所有具体功能名称
					  String r_wIDS=","+mm.get("menu_warrant").toString()+",";                     //角色对应最终子节点被选中的具体功能id
					  Map<String, Object> map=new HashMap<String,Object>();
					  map.put("id", mm.get("id"));
					  map.put("pId",0);
					  map.put("name",mm.get("name"));
					  map.put("warrantID",mm.get("warrantID"));
					  newList.add(map);
					  for(int i=0;i<m_warrantID.length;i++){
							  Map<String, Object> map1=new HashMap<String,Object>();
							  map1.put("id", m_warrantID[i]);
							  map1.put("name", m_warrantName[i]);
							  map1.put("pId", mm.get("id"));
							  if(r_wIDS.contains(","+ m_warrantID[i]+",")){
								  map1.put("checked", true);
								  map.put("checked", true);
							  }
							  newList.add(map1);
					  }
				}
			 }
		}
		return newList;
	}
	/**
	 * 修改角色对应的菜单的具体授权
	 * @param checkNodesJson
	 * @return
	 * @throws Exception
	 */
	public boolean updateRoleAuthorizedList(String checkNodesJson,HttpSession session)throws Exception{
		boolean tag=false;
		try{
			
			JSONArray jsonArr =JSONArray.fromObject(checkNodesJson);
			Map<String, Object>userMap=(Map<String, Object>)session.getAttribute(ICommonConstants.LOGIN_USER);
			StringBuffer sql=new StringBuffer();
			sql.append(" update shop_cm_role_warrant set menu_warrant=null,menu_warrant_names=null where role_id in (").append(userMap.get("role_id")).append(")");
			dbHelper.update(sql.toString());
			for(int i=0;i<jsonArr.size();i++){
				JSONObject mobj=jsonArr.getJSONObject(i);
				if(!mobj.containsKey("warrantID")){
					continue;
				}
				String warrantID=mobj.get("warrantID").toString();  //角色对应授权菜单的id
				String menu_warrant="";
				String menu_warrantNames="";
				JSONArray mobjArr=mobj.getJSONArray("children");
				for(int j=0;j<mobjArr.size();j++){
					JSONObject wobj=mobjArr.getJSONObject(j);
					 if(wobj.getBoolean("checked"))
					 {
						String id=wobj.getString("id");
						String name=wobj.getString("name");
						if(menu_warrant.equals("")){
							menu_warrant=id;
							menu_warrantNames=name;
						}else{
							menu_warrant+=","+id;
							menu_warrantNames+=","+name;
						}
					 }
				}
				 sql=new StringBuffer();
				sql.append(" update shop_cm_role_warrant set menu_warrant='").append(menu_warrant).append("'")
				   .append(" ,menu_warrant_names='").append(menu_warrantNames).append("'")
				   .append(" where id='").append(warrantID).append("'");
				int a=dbHelper.update(sql.toString());
			}
			tag=true;
		}catch(Exception e){
			tag=false;
			logger.error(e.getMessage(),e);
			throw e;
		}
		return tag;
	}
	/**
	 *  修改用户对应的角色
	 * @param infoJsonStr   授权内容
	 * @param userID      需要授权的用户id
	 * @return
	 */
	public boolean updateUserRole(String infoJsonStr,String userID)throws Exception{
		boolean tag=false;
		try{
			//删除用户对应的授权角色
			dbHelper.delete("delete from shop_cm_employee_role where employee_id='"+userID+"'");
			//所属分组进行处理
			JSONArray grouparr=JSONArray.fromObject(infoJsonStr);
			  for(int i=0;i<grouparr.size();i++){
					JSONObject job=(JSONObject) grouparr.get(i);
					@SuppressWarnings("unchecked")
					Map<String, Object> addMap=JSONUtil.getMapFromJsonString(job.toString());
					dbHelper.saveMap(addMap, "shop_cm_employee_role");
				}
			  tag=true;
		}catch(Exception e){
			tag=false;
			logger.error(e.getMessage(),e);
			throw e;
		}
		return tag;
	}
	/**
	 * 添加,修改角色
	 * @param paramMap
	 * @return
	 */
	public boolean saveRole(Map<String,Object> roleMap)throws Exception{
		boolean tag=false;
		try{
			Map<String, Object> keyMap = new HashMap<>();
			StringBuffer sql=new StringBuffer();
			if(roleMap.get("id")!=null && !roleMap.get("id").toString().equals("")){  //本次时编辑角色
				keyMap.put("role_id", roleMap.get("id").toString());
				sql.append("delete from shop_cm_role_warrant where role_id=:role_id");
				dbHelper.delete(sql.toString(),keyMap);           //删除授权菜单
				dbHelper.updateMap(roleMap, "shop_cm_role");  //修改角色信息
			}else{ //新增角色
				roleMap.put("id", IID.getIID());
				dbHelper.saveMap(roleMap, "shop_cm_role");   //保存角色信息
			}
			if(roleMap.get("menu_ids")!=null && !roleMap.get("menu_ids").toString().equals("")){
				String [] menu_ids=roleMap.get("menu_ids").toString().split(",");     //授权菜单id集合
				String [] menu_names=roleMap.get("menu_names").toString().split(","); //授权菜单名称集合
				for(int i=0;i<menu_ids.length;i++){
					sql=new StringBuffer();
					sql.append("  insert into shop_cm_role_warrant (id,role_id,menu_id,menu_name,parent_id,serial_num,final_node)")
					   .append("  select '").append(IID.getIID()).append("','").append(roleMap.get("id")).append("'")
					   .append("   ,id,name,parent_id,serial_num,final_node from shop_cm_menu where id=").append(menu_ids[i])
					   .append("");
					dbHelper.update(sql.toString());   //保存角色授权信息
				}
			}
			tag=true;
		}catch(Exception e){
			logger.error(e.getMessage(),e);
			throw e;
		}
		return tag;
	}
	
	/**
	 *  根据id查询角色
	 * @param id
	 * @return
	 * @throws Exception 
	 */
	public Map<String, Object> queryRoleMapById(String id) throws Exception {
		StringBuilder sql = new StringBuilder();
		sql.append("   select r.id,r.name,r.remark,r.create_user_id,r.create_time,r.update_user_id,r.last_update_time ")
		   .append("   ,ifnull((")
		   .append("      select group_concat(menu_name) menu_name from shop_cm_role_warrant where role_id=r.id")
		   .append("    ),'')menu_names")
		   .append("   ,ifnull((")
		   .append("      select group_concat(menu_id) menu_id from shop_cm_role_warrant where role_id=r.id")
		   .append("    ),'')menu_ids")
		   .append("   from shop_cm_role r where r.id='").append(id).append("' order by r.name")
		   .append("");
		return dbHelper.queryForMap(sql.toString());
	}
	
	
	
	/**
	 * 删除角色级角色对应的授权信息
	 * @param id
	 * @return
	 */
	public boolean deleteRole(String id)  throws Exception {
		boolean tag=false;
		try{
			Map<String, Object> keyMap = new HashMap<>();
			keyMap.put("id", id);
			int delete = dbHelper.delete(keyMap, "shop_cm_role");
			StringBuffer sql=new StringBuffer();
			sql.append("delete from shop_cm_role_warrant where role_id='").append(id).append("'");
			delete=dbHelper.delete(sql.toString());
			tag=delete>0?true:false;
		}catch(Exception e){
			logger.error(e.getMessage(),e);
			throw e;
		}
	    return tag;
	}
	/**
	 * 判断是否有账号绑定了此角色
	 * @return
	 */
	public boolean queryRoleByBind(String roleID)throws Exception{
		boolean tag=false;
		StringBuilder sql = new StringBuilder();
		sql.append("select 1 from shop_cm_employee where role_id='").append(roleID).append("'");
		List<Map<String, Object>> sublist=dbHelper.queryForList(sql.toString(), null);
		if(sublist!=null && sublist.size()>0){
			tag=true;
		}
		return tag;
	}

	/**
	 * 查询角色对应的某个菜单的具体功能授权
	 * @param menuPath  页面路径
	 * @param role_id   用户角色（多个角色逗号分隔）
	 * @return
	 */
	public String queryFeaturesByRole(String menuPath,String role_id)throws Exception{
		String menu_warrant="";
		StringBuilder sql = new StringBuilder();
		sql.append("   select ifnull(group_concat(w.menu_warrant),'') menu_warrant")
		   .append("   from shop_cm_role_warrant w")
		   .append("   left join shop_cm_menu m on w.menu_id=m.id ")
		   .append("   where  w.role_id  in (").append(role_id).append(")")
		   .append("   and m.menu_url='").append(menuPath).append("'")
		   .append("");
		List<Map<String, Object>> list=dbHelper.queryForList(sql.toString(), null);
		if(list!=null && list.size()>0){
			menu_warrant=list.get(0).get("menu_warrant").toString();
		}
		return menu_warrant;
	}
}
